<template>
  <div o-Container>
    <o-list v-bind:source="list.database"
            v-bind="{created:create,exported:output,viewed:view,modified:modify,searched:search}"/>
    <o-dialog v-bind:source="panel.database" v-bind="{opened:load,closed:load}">
      <template slot="content">
        <o-item v-bind:source="item.database" v-bind="{saved:save,backed:back}"></o-item>
      </template>
    </o-dialog>
    <o-dialog v-bind:source="panel.view.database" v-bind="{opened:load,closed:load}">
      <template slot="content">
        <div class="Operation">
          <!--        <o-item v-bind:source="item.database" v-bind="{saved:save,backed:backViewDB}"></o-item>-->
          <el-button type="success" v-on:click="runSQL">Exec SQL</el-button>
          <el-button type="primary" v-on:click="exportCSV">Export CSV</el-button>
          <el-button type="primary" v-on:click="exportSQL">Export SQL</el-button>
          <el-button type="info" v-on:click="backViewDB">Back</el-button>
        </div>

        <o_editor v-bind:source="editorSource"></o_editor>

        <el-table :data="tableData" style="width: 100%" height="500" highlight-current-row border>
          <el-table-column fixed type="index" :width="tableData.length > 0 ? 50:500"></el-table-column>
          <template v-for="column in tableColumnData">
            <el-table-column :fixed="column.fixed" :prop="column.name" :label="column.name" :width="column.width"
                             resizable show-overflow-tooltip>
              <!--              <template slot-scope="scope">-->
              <!--                <el-popover trigger="hover" placement="top">-->
              <!--                  <p> {{ scope.row[column.name] }}: {{ scope.row[column.name] }}</p>-->
              <!--                </el-popover>-->
              <!--                {{scope.row[column.name]}}-->
              <!--              </template>-->
            </el-table-column>
          </template>
        </el-table>

        <!--        <div v-for="(value,key,index) in tableColumnData">-->
        <!--          {{key}}:{{value}}:{{index}}-->
        <!--        </div>-->
        <!--        {{tableColumnData}}-->

      </template>
    </o-dialog>

    <o-dialog v-bind:source="panel.exportCSV" v-bind="{opened:load,closed:load}">
      <div class="Operation">
        <el-button type="info" v-on:click="backViewDBToCSV">Back</el-button>
      </div>
      <el-input type="textarea" :autosize="{ minRows: 30, maxRows: 30}" placeholder="请输入内容" v-model="csvData">
      </el-input>
    </o-dialog>

  </div>
</template>

<script>
  // import * as o_editor from "./components/Engine/Framework/EditorEngine.vue";
  import o_editor from "@/components/Engine/Framework/EditorEngine";

  export default {
    name: "mms_engine_database_list", /* 这个name暂时不知道用啥用，根据官方文档说的是方便排错的 */
    data() {
      return {
        octopus: this.$parent.octopus,
        list: {
          database: {
            data: {
              id: 18, // 八爪鱼ID
              cellData: [
                {name: "Name", searchKey: "Like", width: 200},
                {name: "TypeID", searchKey: "=", width: "80"},
                {name: "ConnectionData", width: "600"},
                {name: "Enable", searchKey: "=", width: "80"},
                // 过滤要在控件绑定这里做，列表页本身的过滤没有意义
                // {name: "Enable", searchKey: "=", width: "80", filterKey: "=", filterValue: [1]},
                {name: "Note", width: "200", searchKey: "Like"},
                {name: "CreateDate", width: "170"}
              ],
            },
            exportName: '数据库管理'
          },
        },
        item: {
          database: {
            // 以下参数默认由组件内部创建，但是如果有需要，开发人员可在这里提前设置，组件将按照您的预期渲染。
            // cache: false,
            // control: null,
            // dataExtend: null,
            data: {
              id: 18,
              value: "#{param=id}",
              cellData: [{name: "Name"},
                {name: "TypeID"},
                {name: "Enable"},
                {name: "CreateDate"},
                {name: "ConnectionData"},
                {name: "Note"}]
            },
          },
        },
        panel: {
          database: {
            visible: false,
          },
          view: {
            // 关系型数据库查看面板，此功能做好，以后可以有更少的人知道数据库账户和密码信息了。
            database: {
              visible: false,
            },
            // redis 查看面板
            redis: {
              visible: false,
            },
            // mqtt 查看面板
            mqtt: {
              visible: false,
            },
          },
          exportCSV: {
            visible: false,
          }
        },
        editorSource: {
          test: 1
        },
        tableData: [],
        tableColumnData: [],
        csvData: "",
      }
    },
    mounted: function () {
      this.init();
    },
    components: {o_editor},
    methods: {
      init: function () {

      },
      create: function () {
        this.item.database.data.value = null;
        this.item.database.control.load();
        this.panel.database.visible = true;
      },
      output: function (data) {
        // 导出以后，回调这里给客户端操作。
        // 核心思想是cellData包含search数据（不管有没有），回传以后发送export指令，后台api会直接返回导出的数据提供下载。
        // alert("export: get cell data is " + JSON.stringify(data));
      },
      search: function (cell) {
        console.log("search:" + JSON.stringify(cell));
      },
      modify: function (row) {
        this.item.database.data.value = row.ID;
        this.item.database.control.load();
        this.panel.database.visible = true; //打开
      },
      // 打开对应的查询面板
      view: function (row) {
        this.item.database.data.value = row.ID;
        this.tableColumnData = [];
        this.tableData = [];

        // 如果是SQL数据库
        if (row.TypeID == "MySQL") {
          // 设置默认值
          this.editorSource.control.setValue("SELECT * FROM base_user limit 100;");

          this.panel.view.database.visible = true; //打开
        } else {
          this.octopus.tips.warning("控制面板仅支持MySQL数据库。");
        }
      },
      // 保存后回调事件，主控件为主的，子控件依赖主控件的，可在主控件保存后调用子控件的save。
      // 回调时因为数据是全部钩子动态绑定的，唯独因为创建会把保存类型给冲掉，所以这样要回传保存的类型
      save: function (data) {
        if (data.status.code == 200) { // 等于200
          this.octopus.tips.success("[" + data.status.code + "] Data Save Success.");
        }
        this.list.database.control.load();
        this.back();
      },
      runSQL: function () {
        this.tableData = [];
        this.tableColumnData = [];

        let o = this;
        // alert(this.item.database.data.value);
        // 执行SQL语句
        this.octopus.request.api.post("/ESB/Services/Tools/Data/GetSQLData", {
          databaseID: this.item.database.data.value,
          query: this.editorSource.control.getValue()
        }, function (data) {
          if (data.status.code == 200) {

            // 如果大于1行，则开始渲染
            if (data.content.length > 0) {

              let index = 0;
              for (let item in data.content[0]) {
                let columnData = data.content[0][item] + "";
                let columnWidth = columnData.length * 15;
                columnWidth = columnWidth < 70 ? 70 : columnWidth;

                // console.log(item + ":" + data.content[0][item] + ":" + columnWidth);
                o.tableColumnData.push({name: item, width: columnWidth, fixed: index == 0 ? true : false});

                index++;
              }
              // 赋值表格内容
              o.tableData = data.content;
            }

          } else {
            o.octopus.tips.warning(data);
            // console.error(data);
          }
        });
      },
      // 导出CSV文件。
      exportCSV: function () {
        // 可以直接用JS创建SQL语句并打开新页面导出。
        this.panel.exportCSV.visible = true; //取消

        let queryToCsv = "";

        //
        this.tableData.map(row => {
          let sql = "";
          for (let value in row) {
            sql += "," + row[value];
          }
          sql = sql.substring(1);

          queryToCsv += sql + "\r\n";
        });

        this.csvData = queryToCsv;
      },
      // 导出SQL
      exportSQL: function () {
        // 可以直接用JS创建SQL语句并打开新页面导出。
        this.panel.exportCSV.visible = true; //取消

        let queryToSQL = "";

        //
        this.tableData.map(row => {
          let sql_value = "";
          let sql_column = "";
          for (let value in row) {
            sql_column += "," + value;
            if (row[value]) {
              sql_value += ",'" + row[value] + "'";
            } else {
              sql_value += "," + row[value] + "";
            }
          }
          sql_value = "INSERT [TableName] (" + sql_column.substring(1) + ")VALUES(" + sql_value.substring(1) + ");";

          queryToSQL += sql_value + "\r\n";
        });

        this.csvData = queryToSQL;
      },
      back: function () {
        this.panel.database.visible = false; //取消
      },
      backViewDB: function () {
        this.panel.view.database.visible = false; //取消
      },
      backViewDBToCSV: function () {
        this.panel.exportCSV.visible = false; //取消
      },
      iRowStyle: function ({row, rowIndex}) {
        return 'height:35px';
      },
      iHeaderRowStyle: function ({row, rowIndex}) {
        return 'height:35px';
      },
      iCellStyle: function ({row, column, rowIndex, columnIndex}) {
        return 'padding:0px'
      },
      iHeaderCellStyle: function ({row, column, rowIndex, columnIndex}) {
        return 'padding:0px'
      },
      setRowClass: function (row, rowIndex) {
        return "aabbcc";
      }
    },
    props: ["oData"]
  }
</script>

<style scoped>

</style>
